<template>
  <el-dialog 
    v-model="device.show"
    width="500px"
    :close-on-press-escape="false"
    :close-on-click-modal="false"
    append-to-body
    destroy-on-close
    title="设备信息"
  >
    <el-button type="primary" @click="refresh" style="margin-bottom: 10px;">刷新</el-button>
    <el-descriptions :column="1" class="state-desc">
      <el-descriptions-item label="检测状态:">
        <span class="status-text" :class="{ 'status-active': device.state.value == '1' }">
          {{ device.state.value == '1' ? '有' : '无' }}
        </span>
      </el-descriptions-item>
      <el-descriptions-item label="最近上报时间:">{{ parseTime(device.state.occurred, '{y}-{m}-{d} {h}:{i}:{s}') }}</el-descriptions-item>
    </el-descriptions>

    <!-- 动态渲染 z1 ~ z8 -->
    <el-descriptions
      v-for="zone in visibleZones"
      :key="zone.key"
      :column="2"
      class="zone-desc"
    >
      <el-descriptions-item :label="`${zone.key.toUpperCase()}:`">
        <span class="status-text" :class="{ 'status-active': zone.value.value == '1' }">
          {{ zone.value.value == '1' ? '有' : '无' }}
        </span>
      </el-descriptions-item>
      <el-descriptions-item label="最近上报时间:">
        {{ parseTime(zone.value.occurred, '{y}-{m}-{d} {h}:{i}:{s}') }}
      </el-descriptions-item>
    </el-descriptions>
  </el-dialog>
</template>

<script lang="ts" setup>
import { getDevicesDetail } from '../api/devices.api'

const device = reactive({
  show: false,
  row: {} as any,
  state: {
    value: '',
    occurred: ''
  }
})

// 动态获取存在的 z1~z8
const visibleZones = computed(() => {
  const zones: { key: string; value: any }[] = []
  for (let i = 1; i <= 8; i++) {
    const key = `z${i}`
    if (device[key]) {
      zones.push({ key, value: device[key] })
    }
  }
  return zones
})

const openDialog = (currentDevice) => {
  device.show = true
  device.row = currentDevice

  refresh()
}

const refresh = () => {
  // 重置 z1~z8（避免上次残留）
  for (let i = 1; i <= 8; i++) {
    delete device[`z${i}`]
  }

  getDevicesDetail(device.row.deviceId)
  .then((res) => {
    const prop = res.data.property || {}

    device.state = prop.state || { value: '', occurred: '' }

    // 动态挂载存在的 z1~z8
    for (let i = 1; i <= 8; i++) {
      const key = `z${i}`
      if (prop[key] !== undefined) {
        device[key] = prop[key]
      }
    }
  })
}

defineExpose({
  openDialog,
})
</script>

<style lang="scss" scoped>
.state-desc :deep(.el-descriptions__body) {
  padding: 10px 10px 0 10px;
  background-color: #e0f7fa; /* 蓝绿色背景，突出 state */
  border-radius: 4px;
  margin-bottom: 12px;
}

.zone-desc :deep(.el-descriptions__body) {
  padding: 10px 10px 0 10px;
  background-color: #f9f9f9; /* 浅灰背景，区别于 state */
  border: 1px solid #eee;
  border-radius: 4px;
  margin-bottom: 8px;
}

.status-text {
  font-weight: bold;
}
.status-active {
  color: #f56c6c; // Element Plus 的 error 色
}
</style>